<?php

namespace addons\sum\controller\trade;

use addons\sum\controller\Common;
use app\admin\model\sum\trade\Order as TradeOrderModel;
use app\admin\model\sum\Config;
use app\admin\model\sum\trade\Rule as RuleModel;

class Order extends Common
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function index()
    {
        $user = auth_user();
        $params = $this->request->param();
        $type = $params['type'] ?? 'recharge';

        if (!in_array($type, ['recharge'])) {
            $this->error('参数错误');
        }
        $orders = TradeOrderModel::{$type}()->where('user_id', $user->id)->paid()
            ->order('id', 'desc')->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', $orders);
    }


    public function detail()
    {
        $user = auth_user();
        $id = $this->request->param('id');

        $order = TradeOrderModel::where('user_id', $user->id);

        $order = $order->where(function ($query) use($id) {
            return $query->where('id', $id)->whereOr('order_sn', $id);
        });

        $order = $order->find();
        if (!$order) {
            $this->error(__('No Results were found'));
        }
        $order->pay_type_text = $order->pay_type_text;

        $this->success('获取成功', $order);
    }

    /**
     * 提交订单
     * @return void
     */
    public function create()
    {
        $user = auth_user();
        $rule_id = $this->request->param('rule_id');
        if(!$rule_id){
            $this->error(__('参数错误'));
        }
        $rule=RuleModel::field("id,type,title,price,score,days")->where('id',$rule_id)->where('status','normal')->find();
        if(!$rule){
            //我也不想都写成参数错误，还有处理多语言。一般情况不会出现的错误，就这样写吧。公司都宣布解散了，还在处理项目，心塞。
            $this->error(__('参数错误'));
        }
        $pay_money=$rule['price'];
        if(!$pay_money>0){
            $this->error(__('参数错误'));
        }
        $orderData = [];
        $orderData['type'] = $rule['type'];
        $orderData['order_sn'] = get_sn($user->id, 'TO');
        $orderData['user_id'] = $user->id;
        $orderData['status'] = TradeOrderModel::STATUS_UNPAID;
        $orderData['order_amount'] = $pay_money;
        $orderData['pay_fee'] = $pay_money;
        $orderData['remain_pay_fee'] = $pay_money;
        $orderData['platform'] = request()->header('platform');
        $orderData['remark'] = $params['remark'] ?? null;
        $ext = [
            'rule' => $rule
        ];
        $orderData['ext'] = $ext;
        $order = new TradeOrderModel();
        $order->save($orderData);

        $this->success(__('操作成功'), $order);
    }


}
